//Includes
#include <stdio.h>
#include <unistd.h>
#include "stdlib.h"
#include "string.h"
#include "sys/time.h"
#include <mpi.h>

//Defines
#define INCREASE_LENGTH   2
#define NUMBER_LOOP       500

void initArray(char *buffer, const int size);

int main(int argc, char *argv[])
{
	// Variable needed for the timer
	MPI_Init(&argc,&argv);

	//Variable needed for MPI
	const int SOURCE = 0;
	const int DEST = 1;
	int numtasks, rank, size;
	MPI_Status status;

	//Variable needed for the communication
	char *buffer;

	MPI_Comm_size(MPI_COMM_WORLD,&numtasks);
	MPI_Comm_rank(MPI_COMM_WORLD,&rank);
	int loopCounter = 0;

	for(loopCounter = 0; loopCounter < NUMBER_LOOP; loopCounter++)
	{
		size = (loopCounter * INCREASE_LENGTH) + INCREASE_LENGTH;

		buffer = (char*)malloc(size);

		if(rank == SOURCE)
		{
			int timeStart, timeEnd;

			initArray(buffer, size);

			timeStart = MPI_Wtime();

			printf("Source before send \n");
			MPI_Send(buffer, size, MPI_CHAR, DEST, 0, MPI_COMM_WORLD);

			printf("Source before rcv \n");
			MPI_Recv(buffer, size, MPI_CHAR, DEST, 0, MPI_COMM_WORLD, &status);

			timeEnd = MPI_Wtime();

			printf("Source after rcv %d\n", loopCounter);

			printf("Temps execution %f\n", timeStart - timeEnd);
		}
		else
		{
			printf("Dest before rcv \n");
			MPI_Recv(buffer, size, MPI_CHAR, SOURCE, 0, MPI_COMM_WORLD, &status);

			printf("Dest before send \n");
			MPI_Send(buffer, size, MPI_CHAR, SOURCE, 0, MPI_COMM_WORLD);

			printf("Dest after send %d\n", loopCounter);
		}

		free(buffer);
	}

	MPI_Finalize();
}

void initArray(char *buffer, const int size)
{
	int loopCounter;

	for(loopCounter = 0; loopCounter < size; loopCounter++)
	{
		buffer[loopCounter] = 'a';
	}
}
